<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>数据应用-数据源</title>

    <link rel="stylesheet" href="../../plugins/fontawesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
    <link rel="stylesheet" href="../../plugins/select2/css/select2.min.css">
    <link rel="stylesheet" href="../../plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">
    <link rel="stylesheet" href="../../plugins/codemirror/codemirror.css">
    <link rel="stylesheet" href="../../plugins/codemirror/theme/darcula.css">
    <link rel="stylesheet" href="../../plugins/codemirror/addon/hint/show-hint.css">
    <link rel="stylesheet" href="../../adminLTE/css/adminlte.min.css">
    <link rel="stylesheet" href="../css/cloud.css">
</head>
<body class="content-wrapper" style="padding: 15px">
<!--顶部条-->
<div style="padding: 0 7px 15px 7px" class="clearfix">
    <!--搜索输入框组-->
    <div class="input-group pull-left" style="width: 50%">
        <input id="keyword" class="form-control" type="search" placeholder="名称/连接地址">
        <div class="input-group-append">
            <button id="search" class="btn btn-info btn-flat"><i class="fa fa-search"></i></button>
        </div>
    </div>
    <!--新增按钮-->
    <button id="add" class="btn btn-info pull-right"><i class="fa fa-plus"></i> 新建数据源</button>
</div>
<!--数据展示-->
<div class="container-fluid">
    <table id="table" class="table table-sm table-hover table-bordered">
        <thead><tr>
            <th style="width: 4em"><input type="checkbox" style="display: none;"> #</th>
            <th>名称</th>
            <th style="width: 5em">类型</th>
            <th>IP地址</th>
            <th style="width: 4em">端口</th>
            <th>数据库</th>
            <th>用户名</th>
            <th style="width: 6em">连接状态</th>
            <th style="width: 6em">责任人</th>
            <th style="width: 6em; display: none">超级用户</th>
            <th style="width: 11em">操作</th>
        </tr></thead>
        <tbody><tr>
            <td><input type="checkbox" style="display: none;" data-id="{{id}}"> {{index}}</td>
            <td>{{name}}</td>
            <td><span class="badge {{typeClass}}">{{type}}</span></td>
            <td>{{host}}</td>
            <td>{{port}}</td>
            <td>{{db}}</td>
            <td>{{user}}</td>
            <td><span class="badge {{statusClass}}">{{status}}</span></td>
            <td>{{owner}}</td>
            <td style="display: none"><span class="badge {{superClass}}" title="{{superUser}}">{{super}}</span></td>
            <td>
                <button class="btn btn-xs btn-outline-primary modify" data-id="{{id}}">
                    <i class="fa fa-pencil"></i> 编辑
                </button>
                <button class="btn btn-xs btn-outline-danger remove" data-id="{{id}}">
                    <i class="fa fa-times"></i> 删除
                </button>
                <div class="btn-group">
                    <button type="button" class="btn btn-xs btn-outline-info dropdown-toggle dropdown-icon" data-toggle="dropdown">
                        <i class="fa fa-list-ul"></i> 更多
                    </button>
                    <div class="dropdown-menu dropdown-menu-outline-info dropdown-menu-right">
                        <a class="dropdown-item dropdown-item-xs super" data-id="{{id}}"  href="javascript:void(0);" style="display: none"><i class="fa fa-user-circle"></i> 补充超级用户</a>
                        <a class="dropdown-item dropdown-item-xs clone" data-id="{{id}}"  href="javascript:void(0);"><i class="fa fa-copy"></i> 复制</a>
                        <a class="dropdown-item dropdown-item-xs more" data-id="{{id}}" href="javascript:void(0);"><i class="fa fa-commenting-o"></i> 详情</a>
                        <a class="dropdown-item dropdown-item-xs line" data-id="{{id}}" href="javascript:void(0);"><i class="fa fa-clock-o"></i> 时间线</a>
                        <a class="dropdown-item dropdown-item-xs execute" data-id="{{id}}" href="javascript:void(0);"><i class="fa fa-file-code-o"></i> 执行SQL查询</a>
                        <a class="dropdown-item dropdown-item-xs backup-plan" data-id="{{id}}" href="javascript:void(0);" style="display: none"><i class="fa fa-calendar"></i> 建立备份计划</a>
                        <a class="dropdown-item dropdown-item-xs backup-history" data-id="{{id}}" href="javascript:void(0);" style="display: none"><i class="fa fa-paste"></i> 建立备份任务</a>
                    </div>
                </div>
            </td>
        </tr>
        </tbody>
    </table>
</div>
<!--加载更多-->
<div id="load-more" class="text-sm-center text-primary" style="display: none;">
    <span style="cursor: pointer"><i class="fa fa-hand-o-right"></i> 点击加载更多数据</span>
</div>
<!--正在加载-->
<div id="loading" class="text-sm-center text-gray" style="display: none;">
    <span><i class="fa fa-refresh fa-spin"></i> 正在加载...</span>
</div>
<!--全部加载-->
<div id="load-all" class="text-sm-center text-success" style="display: none;">
    <i class="fa fa-info-circle"></i> 已加载全部数据
</div>
<!--加载失败-->
<div id="load-error" class="text-sm-center text-danger" style="display: none;">
    <i class="fa fa-exclamation-triangle"></i> 加载失败
</div>
<!--详情-->
<div id="detail" class="side-panel right width400 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <input type="hidden" id="id" name="id">
        <div class="form-group">
            <label for="name" class="require">名称</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="请填写数据源名称" required>
        </div>
        <div class="form-group">
            <label for="type" class="require">类型</label>
            <div class="select2-info">
                <select class="select2" data-dropdown-css-class="select2-info" data-placeholder="请选择数据源类型"
                        id="type" name="type" style="width: 100%;" required></select>
            </div>
        </div>
        <div class="form-group">
            <label for="host" class="require">IP地址</label>
            <input type="text" class="form-control" id="host" name="host" placeholder="请填写IP地址" required>
        </div>
        <div class="form-group">
            <label for="port" class="require">端口</label>
            <input type="number" max="65535" min="0" class="form-control" id="port" name="port" placeholder="请填写端口" required>
        </div>
        <div class="form-group">
            <label for="port" class="require">数据库</label>
            <input type="text" class="form-control" id="db" name="db" placeholder="请填写数据库名称" required>
        </div>
        <div class="form-group">
            <label for="user" class="require">用户名</label>
            <input type="text" class="form-control" id="user" name="user" placeholder="请填写用户名" required>
        </div>
        <div class="form-group">
            <label for="pass" class="require">密码</label>
            <input type="password" class="form-control" id="pass" name="pass" placeholder="请填写密码" required>
        </div>
        <div class="form-group">
            <label for="ownerId" class="require">责任人</label>
            <div class="select2-info">
                <select class="select2" data-dropdown-css-class="select2-info" data-placeholder="请选择责任人"
                        id="ownerId" name="ownerId" style="width: 100%;" required></select>
            </div>
        </div>
        <div class="bg-white">
            <button id="ok" class="btn btn-info"><i class="fa fa-check"></i> 确定</button>
            <button id="cancel" class="btn btn-default"><i class="fa fa-times"></i> 取消</button>
        </div>
    </div>
</div>
<!--克隆-->
<div id="clone-panel" class="side-panel right width400 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <input type="hidden" id="clone-id" name="id">
        <div class="form-group">
            <label for="clone-name" class="require">名称</label>
            <input type="text" class="form-control" id="clone-name" name="name" placeholder="请填写数据源名称" required>
        </div>
        <div class="bg-white">
            <button id="clone-ok" class="btn btn-info"><i class="fa fa-check"></i> 确定</button>
            <button id="clone-cancel" class="btn btn-default"><i class="fa fa-times"></i> 取消</button>
        </div>
    </div>
</div>
<!--执行-->
<div id="execute-panel" class="side-panel right width1000 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <input type="hidden" id="execute-id" name="id">
        <textarea id="execute-sql" name="sql"></textarea>
        <div id="execute-card" class="card" style="margin-top: 20px; display: none;">
            <div class="card-body table-responsive p-0" style="max-height: 350px">
                <table id="execute-result" class="table table-sm table-bordered table-head-fixed">
                    <thead><tr></tr></thead>
                    <tbody><tr></tr></tbody>
                </table>
            </div>
        </div>
        <div class="bg-white" style="margin-top: 20px">
            <button id="execute-ok" class="btn btn-info"><i class="fa fa-check"></i> 执行</button>
            <button id="execute-cancel" class="btn btn-default"><i class="fa fa-times"></i> 取消</button>
        </div>
    </div>
</div>
<!--更多-->
<div id="more-panel" class="side-panel right width1000 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <div class="container-fluid">
            <div id="more-panel-datasource-info">
                <div class="row" style="margin-bottom: 15px">
                    <div class="col-md-4">名称: {{name}}</div>
                    <div class="col-md-4">类型: <span class="badge {{typeClass}}">{{type}}</span></div>
                    <div class="col-md-4">状态: <span class="badge {{statusClass}}">{{status}}</span></div>
                </div>
                <div class="row" style="margin-bottom: 15px">
                    <div class="col-md-4">IP地址: {{host}}</div>
                    <div class="col-md-4">端口: {{port}}</div>
                    <div class="col-md-4">数据库: {{db}}</div>
                </div>
                <div class="row" style="margin-bottom: 15px">
                    <div class="col-md-4">用户名: {{user}}</div>
                    <div class="col-md-4">责任人: {{owner}}</div>
                </div>
            </div>
            <div id="more-panel-table-container" class="row" style="margin-bottom: 15px">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <label class="card-title"></label>
                            <div class="card-tools">
                                <div class="input-group input-group-sm" style="width: 200px;">
                                    <input id="more-panel-table-search-input" type="text" class="form-control float-right" placeholder="名称/注释">
                                    <div class="input-group-append">
                                        <button id="more-panel-table-search-button" class="btn btn-primary"><i class="fa fa-search"></i></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-body table-responsive p-0" style="max-height: 500px">
                            <table class="table table-sm table-hover table-head-fixed">
                                <thead><tr>
                                    <th>#</th>
                                    <th>名称</th>
                                    <th>主键</th>
                                    <th>注释</th>
                                    <th style="width: 5em;">操作</th>
                                </tr></thead>
                                <tbody><tr>
                                    <td>{{index}}</td>
                                    <td><a class="more" href="javascript:void(0)">{{name}}</a></td>
                                    <td>{{key}}</td>
                                    <td>{{comment}}</td>
                                    <td><button class="btn btn-xs btn-outline-info sql" data-name="{{name}}"><i class="fa fa-file-code-o"></i> SQL</button></td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div id="more-panel-column-container" class="row" style="margin-bottom: 15px">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <label class="card-title"></label>
                        </div>
                        <div class="card-body table-responsive p-0" style="max-height: 500px">
                            <table class="table table-sm table-hover table-head-fixed">
                                <thead><tr>
                                    <th>#</th>
                                    <th>名称</th>
                                    <th>类型</th>
                                    <th style="width: 5em;">可否为空</th>
                                    <th style="width: 5em;">是否自增</th>
                                    <th>注释</th>
                                </tr></thead>
                                <tbody><tr>
                                    <td>{{index}}</td>
                                    <td>{{name}}</td>
                                    <td>{{type}}</td>
                                    <td><span class="badge {{nullableClass}}">{{nullable}}</span></td>
                                    <td><span class="badge {{incrementClass}}">{{increment}}</span></td>
                                    <td>{{comment}}</td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="bg-white">
            <button id="more-cancel" class="btn btn-default"><i class="fa fa-times"></i> 关闭</button>
            <button id="more-back" class="btn btn-info"><i class="fa fa-chevron-left"></i> 返回数据表</button>
        </div>
    </div>
</div>
<!--SQL-->
<div id="sql-panel" class="side-panel right width1000 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <textarea id="show-sql"></textarea>
        <div class="bg-white" style="margin-top: 20px">
            <button id="sql-cancel" class="btn btn-default"><i class="fa fa-times"></i> 关闭</button>
            <button id="sql-copy" class="btn btn-info"><i class="fa fa-copy"></i> 复制</button>
            <div class="select2-info pull-right" style="width: 150px; display: inline-block">
                <select id="sql-datasource-type" class="select2" data-dropdown-css-class="select2-info" style="width: 100%;"></select>
            </div>
            <div class="select2-info pull-right" style="width: 150px; display: inline-block">
                <select id="sql-datasource-case" class="select2" data-dropdown-css-class="select2-info" style="width: 100%;"></select>
            </div>
        </div>
    </div>
</div>
<!--SUPER-->
<div id="super-panel" class="side-panel right width400 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <input type="hidden" id="super-id" name="id">
        <div class="form-group">
            <label for="super-user" class="require">用户名</label>
            <input type="text" class="form-control" id="super-user" name="user" placeholder="请填写用户名" required>
        </div>
        <div class="form-group">
            <label for="super-pass" class="require">密码</label>
            <input type="password" class="form-control" id="super-pass" name="pass" placeholder="请填写密码" required>
        </div>
        <div class="bg-white">
            <button id="super-ok" class="btn btn-info"><i class="fa fa-check"></i> 确定</button>
            <button id="super-cancel" class="btn btn-default"><i class="fa fa-times"></i> 取消</button>
        </div>
    </div>
</div>

<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/select2/js/select2.full.min.js"></script>
<script src="../../plugins/codemirror/codemirror.js"></script>
<script src="../../plugins/codemirror/mode/sql/sql.js"></script>
<script src="../../plugins/codemirror/addon/hint/show-hint.js"></script>
<script src="../../plugins/codemirror/addon/hint/sql-hint.js"></script>
<script src="../../plugins/clipboard/clipboard.min.js"></script>
<script src="../js/common.js"></script>
<script src="../js/child.js"></script>
<script>
    var executeSqlArea = CodeMirror.fromTextArea(document.getElementById("execute-sql"), {
        mode: "text/x-sql",
        theme: "darcula"
    });
    var showSqlArea = CodeMirror.fromTextArea(document.getElementById("show-sql"), {
        mode: "text/x-sql",
        theme: "darcula"
    });
    showSqlArea.setSize("auto", "auto");

    var select2TypeCtrl = new Select2Ctrl("#type", Url.dataService.dataSourceTypePage, "name", "value", "select2");
    select2TypeCtrl.init();

    var select2OwnerCtrl = new Select2Ctrl("#ownerId", Url.baseService.userPage, "id", "userName", "select2");
    select2OwnerCtrl.init();

    var select2SqlDataSourceTypeCtrl = new Select2Ctrl("#sql-datasource-type", Url.dataService.dataSourceTypePage, "name", "value", "select2");
    select2SqlDataSourceTypeCtrl.init();

    var select2SqlDataSourceCaseCtrl = new Select2Ctrl("#sql-datasource-case", Url.dataService.dataSourceCasePage, "name", "value", "select2");
    select2SqlDataSourceCaseCtrl.init();

    var tableCtrl = new TableCtrl(
        Url.dataService.dataSourceSearchByKeyword,
        Url.dataService.dataSourceDetail,
        Url.dataService.dataSourceCreate,
        Url.dataService.dataSourceModify,
        Url.dataService.dataSourceRemove,
        function (template, record, index) {
            var statusClass = "bg-warning";
            switch (record.status) {
                case "NORMAL": statusClass = "bg-success"; break;
                case "ABNORMAL": statusClass = "bg-danger"; break;
                case "WAITING": statusClass = "bg-warning"; break;
                case "BACKUPING": statusClass = "bg-info"; break;
                case "REVOCERING": statusClass = "bg-info"; break;
                case "UPGRADING": statusClass = "bg-info"; break;
                default: statusClass = "bg-warning"; break;
            }
            var typeClass = record.type === "MYSQL" ? "bg-info" : "bg-warning";
            var superClass = record.superUser && record.superUser.length > 0 ? "bg-success" : "bg-danger";
            var superInfo = record.superUser && record.superUser.length > 0 ? "已有" : "暂无";

            return template
                .replace(new RegExp("{{index}}", "gm"), index + 1)
                .replace(new RegExp("{{id}}", "gm"), record.id)
                .replace(new RegExp("{{name}}", "gm"), record.name)
                .replace(new RegExp("{{typeClass}}", "gm"), typeClass)
                .replace(new RegExp("{{type}}", "gm"), record.typeValue)
                .replace(new RegExp("{{url}}", "gm"), record.url)
                .replace(new RegExp("{{host}}", "gm"), record.host)
                .replace(new RegExp("{{port}}", "gm"), record.port)
                .replace(new RegExp("{{db}}", "gm"), record.db)
                .replace(new RegExp("{{user}}", "gm"), record.user)
                .replace(new RegExp("{{statusClass}}", "gm"), statusClass)
                .replace(new RegExp("{{status}}", "gm"), record.statusValue)
                .replace(new RegExp("{{superClass}}", "gm"), superClass)
                .replace(new RegExp("{{superUser}}", "gm"), record.superUser)
                .replace(new RegExp("{{super}}", "gm"), superInfo)
                .replace(new RegExp("{{owner}}", "gm"), record.owner ? record.owner.userName : "")
        },
        function () {
            var record = {};
            record.id = $("#id").val();
            record.name = $("#name").val();
            record.type = $("#type").val();
            record.host = $("#host").val();
            record.port = $("#port").val();
            record.db = $("#db").val();
            record.user = $("#user").val();
            record.pass = $("#pass").val();
            record.ownerId = $("#ownerId").val();
            return record;
        },
        "name", "ASC",
    );
    tableCtrl.extraShowCreate = function() {
        $("#ownerId").val(parent.window.frameCtrl.authCtrl.session.id).trigger("change");
    };

    tableCtrl.showClone = function (id) {
        var record = this.getById(id);
        $("#clone-id").val(id);
        $("#clone-name").val(record.name + "-副本");
        $("#clone-panel").removeClass("hide");
    };
    tableCtrl.doClone = function() {
        var self = this;
        var valid = true;
        var record = {};
        record.id = $("#clone-id").val();
        record.name = $("#clone-name").val();
        if (Utils.isEmpty(record.name)) {
            valid = false;
            $("#clone-name").removeClass("is-valid").addClass("is-invalid");
        } else {
            $("#clone-name").removeClass("is-invalid").addClass("is-valid");
        }
        if (!valid) return;
        $.ajax({
            url: Url.dataService.dataSourceClone.replace("{id}", record.id),
            type: HttpMethod.patch,
            contentType: ContentType.text,
            data: record.name,
            success: function (result, status, xhr) {
                $("#clone-panel").addClass("hide");
                record = result;
                self.records.push(record);
                self.setRecords();
                parent.window.frameCtrl.toastr.success("克隆成功！");
            }
        });
    };
    tableCtrl.bindCloneEvent = function() {
        var self = this;
        // 绑定修改按钮
        $("#table").on("click", ".clone", function () {
            var id = $(this).attr("data-id");
            self.showClone(id);
        });
        // 绑定确定按钮
        $("#clone-ok").bind("click", function () {
            self.doClone();
        });
        // 绑定取消按钮
        $("#clone-cancel").bind("click", function () {
            $("#clone-panel").addClass("hide");
        });
    };

    tableCtrl.showSuper = function (id) {
        var record = this.getById(id);
        $("#super-id").val(id);
        if (record.type === "MYSQL") {
            $("#super-user").val("root");
        } else if (record.type === "DM") {
            $("#super-user").val("SYSDBA");
        }
        $("#super-panel").removeClass("hide");
    };
    tableCtrl.doSuper = function() {
        var self = this;
        var valid = true;
        var record = {};
        record.id = $("#super-id").val();
        record.user = $("#super-user").val();
        record.pass = $("#super-pass").val();
        if (Utils.isEmpty(record.user)) {
            valid = false;
            $("#super-user").removeClass("is-valid").addClass("is-invalid");
        } else {
            $("#super-user").removeClass("is-invalid").addClass("is-valid");
        }
        if (Utils.isEmpty(record.pass)) {
            valid = false;
            $("#super-pass").removeClass("is-valid").addClass("is-invalid");
        } else {
            $("#super-pass").removeClass("is-invalid").addClass("is-valid");
        }
        if (!valid) return;
        $.ajax({
            url: Url.dataService.dataSourceSuper.replace("{id}", record.id),
            type: HttpMethod.patch,
            contentType: ContentType.json,
            data: JSON.stringify(record),
            success: function (result, status, xhr) {
                $("#super-panel").addClass("hide");
                var line = self.getById(record.id);
                line.superUser = record.user;
                line.superPass = record.pass;
                self.setRecords();
                parent.window.frameCtrl.toastr.success("补充成功！");
            }
        });
    };
    tableCtrl.bindSuperEvent = function() {
        var self = this;
        // 绑定修改按钮
        $("#table").on("click", ".super", function () {
            var id = $(this).attr("data-id");
            self.showSuper(id);
        });
        // 绑定确定按钮
        $("#super-ok").bind("click", function () {
            self.doSuper();
        });
        // 绑定取消按钮
        $("#super-cancel").bind("click", function () {
            $("#super-panel").addClass("hide");
        });
    };

    tableCtrl.showExecute = function (id) {
        var record = this.getById(id);
        $("#execute-id").val(id);
        $("#execute-panel").removeClass("hide");
    };
    tableCtrl.doExecute = function() {
        var self = this;
        var record = {};
        record.id = $("#execute-id").val();
        record.sql = executeSqlArea.getValue();
        if (Utils.isEmpty(record.sql)) {
            parent.window.frameCtrl.toastr.error("请填写要执行的SQL脚本");
            return;
        }
        $.ajax({
            url: Url.dataService.dataSourceQuery.replace("{id}", record.id),
            type: HttpMethod.patch,
            contentType: ContentType.text,
            data: record.sql,
            success: function (result, status, xhr) {
                $("#execute-result thead tr").html("");
                $("#execute-result tbody").html("");
                for (var i = 0; i < result.length; i++) {
                    var line = result[i];
                    if (i == 0) {
                        for (let key in line) {
                            $("#execute-result thead tr").append("<th>" + key + "</th>")
                        }
                    }
                    var html = "<tr>";
                    for (let key in line) {
                        html += "<td>" + line[key] + "</td>"
                    }
                    html += "</tr>";
                    $("#execute-result tbody").append(html);
                }
            },
            error: function (xhr, error, exception) {
                $("#execute-result thead tr").html("<td style='text-align: center'>异常信息</td>");
                $("#execute-result tbody").html("<tr><td>" + xhr.responseText + "</td></tr>");
            },
            beforeSend: function (xhr) {
                $("#execute-ok").attr("disabled", "disabled");
                $("#execute-card").hide();
            },
            complete: function (xhr, ts) {
                $("#execute-ok").removeAttr("disabled");
                $("#execute-card").show();
            }
        });
    };
    tableCtrl.bindExecuteEvent = function (){
        var self = this;
        // 绑定执行按钮
        $("#table").on("click", ".execute", function () {
            var id = $(this).attr("data-id");
            self.showExecute(id);
        });
        // 绑定确定按钮
        $("#execute-ok").bind("click", function () {
            self.doExecute();
        });
        // 绑定取消按钮
        $("#execute-cancel").bind("click", function () {
            $("#execute-panel").addClass("hide");
        });
    };

    tableCtrl.moreRecord = null;
    tableCtrl.moreTable = null;
    tableCtrl.moreDataSourceTemplate = "";
    tableCtrl.moreDataTableListTemplate = "";
    tableCtrl.moreDataColumnListTemplate = "";
    tableCtrl.getMoreTemplate = function() {
        this.moreDataSourceTemplate = $("#more-panel-datasource-info").html();
        this.moreDataTableListTemplate = $("#more-panel-table-container table tbody").html();
        this.moreDataColumnListTemplate = $("#more-panel-column-container table tbody").html();
        $("#more-panel-datasource-info").html("");
        $("#more-panel-table-container table tbody").html("");
        $("#more-panel-column-container table tbody").html("");
    };
    tableCtrl.getMoreRecord = function (id) {
        var self = this;
        $.ajax({
            url: Url.dataService.dataSourceMore.replace("{id}", id),
            type: HttpMethod.get,
            success: function (result, status, xhr) {
                self.moreRecord = result;
                self.setMoreDataSourceInfo();
                self.setMoreRecordTables();
                $("#more-panel-table-search-input").val("");

            },
            beforeSend: function (xhr) {
                self.setMoreWaitingSchema();
                $("#more-panel").removeClass("hide");
            },
            complete: function (xhr, ts) {
            }
        });
    };
    tableCtrl.setMoreDataSourceInfo = function () {
        $("#more-panel-datasource-info").html("");
        var statusClass = "bg-danger";
        if (this.moreRecord.basic.status === "NORMAL") {
            statusClass = "bg-success";
        }
        var typeClass = "bg-info";
        if (this.moreRecord.basic.type === "DM") {
            typeClass = "bg-warning";
        }

        var html = this.moreDataSourceTemplate
            .replace(new RegExp("{{name}}", "gm"), this.moreRecord.basic.name)
            .replace(new RegExp("{{typeClass}}", "gm"), typeClass)
            .replace(new RegExp("{{type}}", "gm"), this.moreRecord.basic.typeValue)
            .replace(new RegExp("{{statusClass}}", "gm"), statusClass)
            .replace(new RegExp("{{status}}", "gm"), this.moreRecord.basic.statusValue)
            .replace(new RegExp("{{host}}", "gm"), this.moreRecord.basic.host)
            .replace(new RegExp("{{port}}", "gm"), this.moreRecord.basic.port)
            .replace(new RegExp("{{db}}", "gm"), this.moreRecord.basic.db)
            .replace(new RegExp("{{user}}", "gm"), this.moreRecord.basic.user)
            .replace(new RegExp("{{owner}}", "gm"), this.moreRecord.basic.owner.userName);
        $("#more-panel-datasource-info").html(html);
    };
    tableCtrl.setMoreTableSchema = function () {
        $("#more-panel-table-container").show();
        $("#more-panel-column-container").hide();
        $("#more-back").hide();
    };
    tableCtrl.setMoreColumnSchema = function () {
        $("#more-panel-table-container").hide();
        $("#more-panel-column-container").show();
        $("#more-back").show();
    };
    tableCtrl.setMoreWaitingSchema = function () {
        this.setMoreTableSchema();
        $("#more-panel-datasource-info").html("<div style='text-align: center; margin-bottom: 15px'><span><i class=\"fa fa-refresh fa-spin\"></i> 正在加载...</span></div>");
        $("#more-panel-table-container table tbody").html("<tr style='height: 100px;'><td colspan='5' style='text-align: center; vertical-align: middle;'><span><i class=\"fa fa-refresh fa-spin\"></i> 正在加载...</span></td></tr>");
        $("#more-panel-table-container .card .card-header .card-title").html("");
    };
    tableCtrl.setMoreRecordTables = function (keyword) {
        this.setMoreTableSchema();

        $("#more-panel-table-container .card .card-header .card-title").html(this.moreRecord.basic.url);
        $("#more-panel-table-container table tbody").html("");
        var index = 1;
        for (var i = 0; i < this.moreRecord.tables.length; i++) {
            var record = this.moreRecord.tables[i];
            if (Utils.notEmpty(keyword) && !record.name.includes(keyword) && !record.comment.includes(keyword)) {
                continue;
            }
            var html = this.moreDataTableListTemplate
                .replace(new RegExp("{{index}}", "gm"), (index))
                .replace(new RegExp("{{name}}", "gm"), record.name)
                .replace(new RegExp("{{comment}}", "gm"), record.comment)
                .replace(new RegExp("{{key}}", "gm"), record.primaryKeyValue);
            $("#more-panel-table-container table tbody").append(html);
            index = index + 1;
        }
    };
    tableCtrl.setMoreRecordColumns = function (table) {
        this.setMoreColumnSchema();

        for (var i = 0; i < this.moreRecord.tables.length; i++) {
            var record = this.moreRecord.tables[i];
            if (record.name === table) {
                $("#more-panel-column-container .card .card-header .card-title").html(record.name);
                $("#more-panel-column-container table tbody").html("");
                for (var j = 0; j < record.columns.length; j++) {
                    var column = record.columns[j];

                    var nullableClass = "bg-danger";
                    var nullable = "非空";
                    if (column.nullable) {
                        nullableClass = "bg-success";
                        nullable = "";
                    }

                    var incrementClass = "bg-default";
                    var increment = "";
                    if (column.increment) {
                        incrementClass = "bg-success";
                        increment = "自增";
                    }

                    var html = this.moreDataColumnListTemplate
                        .replace(new RegExp("{{index}}", "gm"), (j + 1))
                        .replace(new RegExp("{{name}}", "gm"), column.name)
                        .replace(new RegExp("{{type}}", "gm"), column.type)
                        .replace(new RegExp("{{nullable}}", "gm"), nullable)
                        .replace(new RegExp("{{nullableClass}}", "gm"), nullableClass)
                        .replace(new RegExp("{{increment}}", "gm"), increment)
                        .replace(new RegExp("{{incrementClass}}", "gm"), incrementClass)
                        .replace(new RegExp("{{comment}}", "gm"), column.comment);
                    $("#more-panel-column-container table tbody").append(html);
                }

                break;
            }
        }
    };
    tableCtrl.getMoreTableSql = function (table, dataSourceType, dataSourceCase) {
        var self = this;
        self.moreTable = table;
        var url = Url.dataService.dataSourceSqlCreateTable.replace("{id}", self.moreRecord.basic.id).replace("{name}", table) + "?t=t";
        if (Utils.notEmpty(dataSourceType)) {
            url += "&dst=" + encodeURIComponent(dataSourceType);
        }
        if (Utils.notEmpty(dataSourceCase)) {
            url += "&ct=" + encodeURIComponent(dataSourceCase);
        }
        var interval;
        $.ajax({
            url: url,
            type: HttpMethod.get,
            success: function (result, status, xhr) {
                clearInterval(interval);
                showSqlArea.setValue(result);
            },
            beforeSend: function (xhr) {
                showSqlArea.setValue("正在加载...");
                interval = setInterval(function () {
                    showSqlArea.setValue(showSqlArea.getValue() + ".");
                }, 500);
                $("#sql-panel").removeClass("hide");
            },
        });
    };
    tableCtrl.bindMoreEvent = function() {
        var self = this;
        // 绑定搜索按钮
        $("#more-panel-table-search-button").click(function () {
            self.setMoreRecordTables($("#more-panel-table-search-input").val());
        });
        // 绑定更多按钮
        $("#table").on("click", ".more", function () {
            var id = $(this).attr("data-id");
            self.getMoreRecord(id);
        });
        // 绑定时间线按钮
        $("#table").on("click", ".line", function () {
            var id = $(this).attr("data-id");
            var record = self.getById(id);
            var uuid = Math.random().toString(36).slice(-8);
            var name = record.name + " 的 " + "时间线";
            var url = "cloud/html/data-source-time-line.html?id=" + id;
            parent.window.frameCtrl.windowCtrl.open(uuid, name, url);
        });
        // 绑定返回按钮
        $("#more-back").bind("click", function () {
            self.setMoreTableSchema();
        });
        // 绑定取消按钮
        $("#more-cancel").bind("click", function () {
            $("#more-panel").addClass("hide");
        });
        // 绑定更多按钮
        $("#more-panel-table-container table tbody").on("click", ".more", function () {
            self.setMoreRecordColumns($(this).html());
        });
        // 绑定表SQL按钮
        $("#more-panel-table-container table tbody").on("click", ".sql", function () {
            $("#sql-datasource-type").val(self.moreRecord.basic.type).trigger("change");
            $("#sql-datasource-case").val("UNCHANGE").trigger("change");
            self.getMoreTableSql($(this).attr("data-name"));
        });
        // 绑定取消按钮
        $("#sql-cancel").bind("click", function () {
            $("#sql-panel").addClass("hide");
        });
        // 绑定复制按钮
        new ClipboardJS('#sql-copy', {
            text: function(trigger) {
                return showSqlArea.getValue();
            }
        }).on('success', function(e) {
            parent.window.frameCtrl.toastr.success("复制成功");
        }).on('error', function(e) {
            parent.window.frameCtrl.toastr.error("复制失败");
        });
        // 绑定建立备份计划按钮
        $("#table").on("click", ".backup-plan", function () {
            parent.window.frameCtrl.windowCtrl.menu("data-backup-plan.html");
        });
        // 绑定建立备份任务按钮
        $("#table").on("click", ".backup-history", function () {
            parent.window.frameCtrl.windowCtrl.menu("data-backup-history.html");
        });
        // 绑定SQL下拉框
        $("#sql-datasource-type, #sql-datasource-case").on("select2:select", function () {
            self.getMoreTableSql(self.moreTable, $("#sql-datasource-type").val(), $("#sql-datasource-case").val());
        });
    };

    tableCtrl.getTemplate();
    tableCtrl.getMoreTemplate();
    tableCtrl.getRecords();
    tableCtrl.bindEvent();
    tableCtrl.bindCloneEvent();
    tableCtrl.bindSuperEvent();
    tableCtrl.bindExecuteEvent();
    tableCtrl.bindMoreEvent();

    var listener = function (event) {
        if (event.type === "DATA_SOURCE_ABNORMAL" ||
            event.type === "DATA_SOURCE_NORMAL" ||
            event.type === "DATA_SOURCE_BACKUP_RUNNING" ||
            event.type === "DATA_SOURCE_BACKUP_SUCCESS" ||
            event.type === "DATA_SOURCE_BACKUP_ERROR" ||
            event.type === "DATA_SOURCE_RECOVERY_RUNNING" ||
            event.type === "DATA_SOURCE_RECOVERY_SUCCESS" ||
            event.type === "DATA_SOURCE_RECOVERY_ERROR" ||
            event.type === "DATA_SOURCE_UPGRADE_RUNNING" ||
            event.type === "DATA_SOURCE_UPGRADE_SUCCESS" ||
            event.type === "DATA_SOURCE_UPGRADE_ERROR"
        ) {
            tableCtrl.refreshById(event.data);
        }
    };
    listener.owner = window.location.href;
    parent.window.frameCtrl.websockerCtrl.eventListener.push(listener);

</script>
</body>
</html>